import { Component, useRef } from "react";
import React from "react";
import "./css/SpeechSynth.scss";
import {
  NavBar,
  Space,
  Form,
  Button,
  TextArea,
  Mask,
  SpinLoading,
} from "antd-mobile";
import withRouter from "./common/WithRouter";
import util from "./common/Util";
import constant from "./common/Constants";
class SpeechSynth extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
    this.formRef = React.createRef();
    this.audioRef = React.createRef();
    this.textRef = React.createRef();
    this.containerRef = React.createRef();
  }
  back = () => {
    const { na } = this.props.router;
    na("/menuList");
  };
  reset = () => {
    this.formRef.current.resetFields();
    this.audioRef.current.src = "";
  };
  submit = () => {
    const { na } = this.props.router;
    const token = util.getToken();
    if (token == null) {
      na("/login");
    }
    const text = this.textRef.current.nativeElement.value;
    var url = constant.baseUrl + "/app/tts";
    this.setState({ visible: true });
    util.postForm(url, { token, text }, (resultObj) => {
      this.setState({ visible: false });
      if (resultObj.code === 50002) {
        localStorage.removeItem("token");
        na("/login");
      }
      var blob = util.base64toBlob(resultObj.audio, "audio/mpeg");
      this.audioRef.current.src = URL.createObjectURL(blob);
    });
  };
  getContainer = () => {
    return this.containerRef.current;
  };

  render() {
    const ret = (
      <div className="SpeechSynth container" ref={this.containerRef}>
        <NavBar onBack={this.back}>语音合成</NavBar>
        <Form
          onFinish={this.submit}
          ref={this.formRef}
          style={{ "--prefix-width": "3.5em" }}
          layout="horizontal"
          footer={
            <div>
              <Space wrap block>
                <Button color="primary" type="submit">
                  提交
                </Button>
                <Button onClick={this.reset}>重置</Button>
              </Space>
              <Space justify="start" className="speech-auio" block>
                <audio controls ref={this.audioRef}></audio>
              </Space>
            </div>
          }
        >
          <Form.Item
            name="address"
            label="文本"
            rules={[{ required: true }, { type: "string", min: 6 }]}
          >
            <TextArea
              ref={this.textRef}
              placeholder="请输入合成文本"
              maxLength={200}
              rows={10}
              showCount
            />
          </Form.Item>
        </Form>

        <Mask visible={this.state.visible}>
          <div className="mask">
            <SpinLoading style={{ "--size": "80px" }} />
          </div>
        </Mask>
      </div>
    );
    return ret;
  }
}
export default withRouter(SpeechSynth);
